﻿using CocoaAni.Net.WebSockets.Enums;
using CocoaAni.Net.WebSockets.Frames;
using System.Text;

namespace CocoaAni.Net.WebSockets.Messages;

public class Message
{
    internal ReceiveBuffer Buffer { get; set; }
    internal int EndIndex { get; set; }

    private byte[]? _data = null;

    public byte[] Data
    {
        get
        {
            if (_data != null) return _data;
            return _data = Buffer.Buffer[0..EndIndex];
        }
        set => _data = value;
    }

    public Memory<byte> DataMemory => Buffer.Buffer.AsMemory(0, EndIndex);

    public Message(ReceiveBuffer buffer)
    {
        Buffer = buffer;
        EndIndex = buffer.PayloadSaveCursor;
        if (buffer.IsCopyDataOnBuildMessage)
        {
            _data = buffer.Buffer[0..EndIndex];
        }
    }

    public WSOpcode Opcode { get; set; } = WSOpcode.Text;
    public bool IsText => Opcode == WSOpcode.Text;
    public bool IsBinary => Opcode == WSOpcode.Binary;

    public string? Text { get; protected set; }

    public override string ToString()
    {
        return Data.Length == 0
            ? string.Empty
            : Text ??= Encoding.UTF8.GetString(Data);
    }
}